/*头文件声明区域*/
#include <STC15F2K60S2.H>
#include <Led.h>
#include <iic.h>
#include <Seg.h>
#include <Key.h>
#include <init.h>
/*变量声明区域*/
unsigned char Key_Slow_Down;
unsigned int Seg_Slow_Down;
unsigned char Seg_Pos;
unsigned char Seg_Buf[8]={10,10,10,10,10,10,10,10};
unsigned char Seg_Point[8]={0,0,0,0,0,0,0,0};
unsigned char ucLed[8]={0,0,0,0,0,0,0,0};
unsigned char Key_Down,Key_Val,Key_Up,Key_Old;
float val;
unsigned char Seg_Mode;//0-电压显示界面，1-电压输出界面
unsigned char val_mode=0;//输出模式专用变量
unsigned int time_200ms;
bit flag;
float val_output;
bit Seg_Flag =1;
/*按键处理模块*/
void Key_Proc()
{
	if(Key_Slow_Down!=0)return;
	Key_Slow_Down=1;
	Key_Val=Key_Read();
	Key_Down=Key_Val&(Key_Old^Key_Val);
	Key_Up=~Key_Val&(Key_Old^Key_Val);
	Key_Old=Key_Val;
	
	switch(Key_Down)
	{
		case 8:
			Seg_Mode^=1;
		break;
		case 9:
			val_mode^=1;
		break;
		case 7:
			Seg_Flag^=1;
		break;
	}
}

/*数码管处理函数*/
void Seg_Proc()
{
	if(Seg_Slow_Down)return;
	Seg_Slow_Down=1;
	//信息获取
	val=Ad_Read(0x43)/51.0;
	if(val_mode==0)
		val_output=2;
	else
		val_output=val;
	
	//数据显示界面
	switch(Seg_Mode)
	{
		case 0:
			Seg_Buf[0]=11;
			Seg_Buf[5]=(unsigned char)val;
			Seg_Buf[6]=(unsigned int)(val*100)/10%10;
			Seg_Buf[7]=(unsigned int)(val*100) %10;
			Seg_Point[5]=1;
		break;
		case 1:
			Seg_Buf[0]=12;
			Seg_Buf[5]=(unsigned char)val_output;
			Seg_Buf[6]=(unsigned int)(val_output*100)/10%10;
			Seg_Buf[7]=(unsigned int)(val_output*100) %10;
			Seg_Point[5]=1;
		break;
		
	}
}

/*Led模块*/
void Led_Proc()
{
	unsigned char i;
	Da_Write(val_output);
	for(i=0;i<2;i++)
	{
		ucLed[i]=(i==Seg_Mode);
	}
	if(val<1.5||val>=2.5&&val<=3.5)
		ucLed[2]=0;
	else
		ucLed[2]=1;
	ucLed[3]=val_output;
}

/*定时器中断服务函数*/

void Timer0_Isr() interrupt 1
{
	if(++Key_Slow_Down==10) Key_Slow_Down=0;
	if(++Seg_Slow_Down==100) Seg_Slow_Down=0;
	if(++Seg_Pos==8) Seg_Pos=0;
	if(Seg_Flag)
		Seg_Disp(Seg_Pos,Seg_Buf[Seg_Pos],Seg_Point[Seg_Pos]);
	else
		Seg_Disp(Seg_Pos,10,0);
	Led_Disp(Seg_Pos,ucLed[Seg_Pos]);
	if(++time_200ms==500)
	{
		time_200ms=0;
		flag^=1;
	}
}

void Timer0_Init()		//1毫秒@12.000MHz
{
	AUXR &= 0x7F;			//定时器时钟12T模式
	TMOD &= 0xF0;			//设置定时器模式
	TL0 = 0x18;				//设置定时初始值
	TH0 = 0xFC;				//设置定时初始值
	TF0 = 0;				//清除TF0标志
	TR0 = 1;				//定时器0开始计时
	ET0 = 1;				//使能定时器0中断
	EA=1;
}

/*Main*/
void main()
{
	init_System();
	Timer0_Init();
	
	while(1)
	{
		Key_Proc();
		Seg_Proc();
		Led_Proc();
		
	}
}
